package com.ms.p2p.controller.wap;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ms.common.bean.Message;
import com.ms.common.exception.NoticeException;
import com.ms.common.utils.*;
import com.ms.p2p.Constants;
import com.ms.p2p.bean.PageBean;
import com.ms.p2p.entity.RetMap;
import com.ms.p2p.entity.loan.Loan;
import com.ms.p2p.entity.member.Member;
import com.ms.p2p.plugin.validation.annotation.RequiredStringValidator;
import com.ms.p2p.plugin.validation.annotation.Validations;
import com.ms.p2p.provider.*;
import com.ms.p2p.service.RSAService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by chensk on 2017/11/28.
 */
@Controller
@RequestMapping({ "/wap" })
public class WapIndexController  extends  WapBaseController{

    @Reference
    private LoanProvider loanProvider;

    @Reference
    private MemberProvider memberProvider;

    @Reference
    private AdvertProvider advertProvider;

    @Reference
    private ArticleProvider articleProvider;
    @Autowired
    private RSAService rsaService;

    @Reference
    private RedPacketCategoryProvider redPacketCategoryProvider;

    /**
     * 登录
     */
    @RequestMapping({ "/member/common/login" })
    public String login() {
        if(getCurrentUser() != null){
            return "redirect:wap/toIndex";
        }

        return "/wap/login";
    }

    /**
     * 登录
     */
    @RequestMapping({ "/member/common/register" })
    public String register(String phone,Model model) {
        if(getCurrentUser() != null){
            return "redirect:wap/index";
        }
        if (StringUtils.isNotBlank(phone)) {
            try {
                phone = new String(Base64Utils.decodeFromString(phone), "utf-8");
                Member user = memberProvider.findByMobilePhone(phone);
                if (user != null) {
                    model.addAttribute("phone", user.getMember_phone());
                }
            } catch (Exception e) {
                logger.error("注册邀请手机转码失败", e);
            }
        }
        return "/wap/register";
    }



    /**
     * 首页
     */
    @RequestMapping({"/index","/toIndex"})
    public String index(Model model)  {
        Loan loan = loanProvider.findRookie();
        PageBean page = new PageBean();
        page.setPageSize(3);
        model.addAttribute("articles", articleProvider.findPager(5, "1", page));
        model.addAttribute("registers",memberProvider.countAllUser());
        model.addAttribute("totalTurnover",loanProvider.totalMoney()==null?"0":loanProvider.totalMoney().get("totalTurnover"));//累计投资
        //文章列表
        model.addAttribute("banners", advertProvider.getPPTList(1,2));
        model.addAttribute("loans",loanProvider.findPager(null,null,null,2,null,null,null,null,null,null,null,null,null,null,page));
        model.addAttribute("rookie",loan);
        model.addAttribute("index",0);
        return "/wap/index/index";
    }
    @Reference
    private SendProvider smsServicesmsService;
    @Reference
    private SettingProvider settingProvider;

    /**
     * 获取
     */
    @RequestMapping({"/rookie"})
    public String rookie(HttpServletRequest request) {
        PageBean a =new PageBean();
        a.setPageSize(100);
        List<HashMap> redpacketCategorys= redPacketCategoryProvider.findPager(a);
        List<HashMap> newred = new ArrayList<HashMap>() ;

        for(HashMap redpacketCategory: redpacketCategorys){

            redpacketCategory.put("tender_time_limit",Integer.parseInt(redpacketCategory.get("tender_time_limit").toString())*30);

            if(redpacketCategory.get("is_disable").toString().equals("1")){

                newred.add(redpacketCategory);
            }
        }

        request.setAttribute("rookies",newred);
        return "/wap/index/rookie";
    }

    /**
     * 登录
     */
    @RequestMapping({ "/forget/{type}" })
    public String forget(@PathVariable String type, Model model) {
        if(getCurrentUser() != null){
           model.addAttribute("mobile",getCurrentUser().getMember_phone());

        }
        model.addAttribute("type",type);
        return "/wap/forget";
    }



    /**
     *	找回密码
     */
    @Validations(requiredStrings = {

            @RequiredStringValidator(fieldName = "mobile", message = "手机号码不能正确"),
            @RequiredStringValidator(fieldName = "captcha", message = "图形验证码不能为空")
    })
    @RequestMapping(value = "/send", method = RequestMethod.POST)
    @ResponseBody
    public String send(String mobile, String captcha, HttpServletResponse response, HttpSession session) throws IOException, TemplateException {
        //验证码校验
        String sessionCaptcha = (String) AppContext.getSessionAttr(Constants.CAPTCHA_SESSION_KEY);
        if (StringUtils.isBlank(sessionCaptcha) || StringUtils.isBlank(captcha) || !sessionCaptcha.toLowerCase().equals(captcha.toLowerCase())) {
            return ResponseUtils.renderJSON(Message.error("图形验证码不能为空"), response);
        }
        if(!sessionCaptcha.equals(captcha)){
            return ResponseUtils.renderJSON(Message.error("图形验证码错误"), response);
        }

        Object mobileCodeSession =  session.getAttribute(Constants.COMMON_MOBILE_CODE_SESSION_KEY);
        if(mobileCodeSession!=null){
            String session1 = mobileCodeSession.toString();
            String[] codes = StringUtils.split(session1, "_");
            if(System.currentTimeMillis() - Long.valueOf(codes[1]) < 1000*10*6){
                throw  new NoticeException("60秒内只能发送一条短信");
            }
        }
        Member user = memberProvider.findByMobilePhone(mobile);
        if(user==null){
            throw  new NoticeException("用户不存在");

        }
        FreeMarkerConfigurer freeMarkerConfigurer = SpringContextHolder.getBean("freeMarkerConfigurer");
        String mobileCode = CommonUtil.getRandomNum(6);
        String nickname = settingProvider.findByCode("email_from_name").getText();
        String templatePath = Constants.TEMPLATE_SMS_BIND;
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Template template = configuration.getTemplate(templatePath, "utf-8");
        HashMap map = new HashMap();
        map.put("code",mobileCode);
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        // 发送短信
        Message message = smsServicesmsService.sendSMS(mobile,"【"+nickname+"】"+content, "找回密码", 0);
        session.setAttribute(Constants.COMMON_MOBILE_CODE_SESSION_KEY,mobileCode + "_" + System.currentTimeMillis());

        return ResponseUtils.renderJSON(message, response);

    }

    /**
     * 退出
     */
    @RequestMapping("/logout")
    public String logout(){
        AppContext.removeAttribute(Constants.PRINCIPAL_SESSION_NAME);
        return "redirect:/wap/index";
    }


    /**
     * 注册
     */
    @Validations(requiredStrings = {

            @RequiredStringValidator(fieldName = "mobile", message = "手机号码不能正确"),
            @RequiredStringValidator(fieldName = "pass1", message = "密码格式不正确"),
            @RequiredStringValidator(fieldName = "mobileCode", message = "手机验证码不能为空")
    })
    @RequestMapping("/register")
    @ResponseBody
    public Message regist(String pass1,String mobile,String inviter,String mobileCode) {
        String username = mobile;
        String mobileCodeSession = (String) AppContext.getSessionAttr(Constants.REGIST_MOBILE_CODE_SESSION_KEY);
        if (StringUtils.isBlank(mobileCodeSession) || !mobileCodeSession.contains("_")) {
            throw new NoticeException("验证码错误或过期无效");
        }

        //验证码验证
        String[] codes = StringUtils.split(mobileCodeSession, "_");
        if(codes == null || codes.length != 2
                || System.currentTimeMillis() - Long.valueOf(codes[1]) > 1000*60*10
                || StringUtils.isBlank(codes[0]) || !StringUtils.equals(codes[0], mobileCode) ){
            throw new NoticeException("验证码错误或过期无效");
        }

        if (pass1.equals(username)) {
            throw new NoticeException("用户名与密码不能相同！");
        }

        if (!(mobile.matches("^1[0-9]{10}$"))) {
            throw new NoticeException("请输入正确的手机号码！");
        }

        if(!username.matches("^[a-zA-z][a-zA-Z0-9_]{3,18}$")){
            throw new NoticeException("用户名长度4-18位，字母、数字、下划线组合，必须以字母开头！");
        }

        String pwdRegex = "^(.*){6,20}$";
        if (!pass1.matches(pwdRegex)) {
            return Message.error("密码必须6-20位");
        }

        if (memberProvider.findByUserName(username) != null) {
            throw new NoticeException("该用户名已注册！");
        }

        if (memberProvider.findByMobilePhone(mobile) != null) {
            throw new NoticeException("该手机号码已注册！");
        }

        Member member = new Member();
        if (inviter != null && !inviter.equals("")) {
            Member remmendUser = memberProvider.findByMobilePhone(inviter);
            if (remmendUser == null) {
                throw new NoticeException("推荐人手机号码不存在");
            }
            member.setLevel(remmendUser.getLevel() + 1);
            member.setFirst_recommend_id(remmendUser.getFirst_recommend_id() == 0 ? remmendUser.getId() : remmendUser.getFirst_recommend_id());
            member.setRecommend_id(remmendUser.getId());
        } else {
            member.setLevel(0);
            member.setFirst_recommend_id(0);
        }
        // 插入注册用户
        member.setUser_name(username.trim());
        member.setMember_phone(mobile);
        member.setLogin_password(DigestUtils.md5Hex(pass1));
        member.setPayment_password(DigestUtils.md5Hex(pass1));
        member.setStatus(0);
        member.setLogin_times(1);
        member.setAdd_ip(AppContext.getRemoteIp());
        member.setAdd_time(MsDateUtils.getTime());
        member.setUp_ip(member.getAdd_ip());
        member.setUp_time(member.getAdd_time());
        member.setLast_ip(member.getAdd_ip());
        member.setLast_time(member.getAdd_time());
        member = memberProvider.register(member);
        AppContext.setSessionAttr(Constants.PRINCIPAL_SESSION_NAME, member);
        AppContext.removeAttribute(Constants.REGIST_MOBILE_CODE_SESSION_KEY);
        //使用

        return Message.success("注册成功");
    }

    /**
     * 修改支付密码
     */
    @Validations(requiredStrings = {
            @RequiredStringValidator(fieldName = "mobile", message = "手机验证码不能为空"),
            @RequiredStringValidator(fieldName = "code", message = "手机验证码不能为空"),
            @RequiredStringValidator(fieldName = "pass1", message = "新密码不能为空"),
            @RequiredStringValidator(fieldName = "pass2", message = "确认密码不能为空")

    })
    @RequestMapping("/password/modify")
    @ResponseBody
    public HashMap modifyPayPwd(HttpSession session,String mobile, String code,  String pass1, String pass2,String type) {
        Member member =   memberProvider.findByMobilePhone(mobile);
        // 密码正则
        String pwdRegex = "^(.*){6,20}$";


        if (!StringUtils.equals(pass1, pass2)) {
            throw new NoticeException("两次输入的密码不一致！");
        }

        if (!pass1.matches(pwdRegex)) {
            throw new NoticeException("密码必须6-20位");
        }


        String mobileCodeSession;
        try {
            mobileCodeSession =  session.getAttribute(Constants.COMMON_MOBILE_CODE_SESSION_KEY).toString();
        }catch (Exception e){
            throw new NoticeException("验证码错误或过期无效");
        }
        if (StringUtils.isBlank(mobileCodeSession) || !mobileCodeSession.contains("_")) {
            throw new NoticeException("验证码错误或过期无效");
        }
        //验证码验证
        String[] codes = StringUtils.split(mobileCodeSession, "_");
        if(codes == null || codes.length != 2 || System.currentTimeMillis() - Long.valueOf(codes[1]) > 1000*60*10 || StringUtils.isBlank(codes[0]) || !StringUtils.equals(codes[0], code) ){
            throw new NoticeException("验证码错误或过期无效");
        }

        session.removeAttribute(Constants.COMMON_MOBILE_CODE_SESSION_KEY);
        if(type.equals("deal"))
        member.setPayment_password(DigestUtils.md5Hex(pass1));
        if(type.equals("safe"))
         member.setLogin_password(DigestUtils.md5Hex(pass1));
        member.setUp_time(String.valueOf(System.currentTimeMillis()));
        member.setUp_ip(AppContext.getRemoteIp());
        memberProvider.updateById(member);

        return RetMap.Success("密码重置成功！");
    }


    @RequestMapping("/loginVerify")
    @ResponseBody

    @Validations(requiredStrings = {
            @RequiredStringValidator(fieldName = "username", message = "用户名不能为空"),
            @RequiredStringValidator(fieldName = "password", message = "密码不能为空"),

    })
    public Message login(String username, String password, String captcha,
                         HttpServletRequest request, HttpSession session) {


        password = rsaService.decryptParameter(password);
        rsaService.removePrivateKey(request);

        if(StringUtils.isBlank(password)){
            return Message.error("您的用户名或密码错误！");
        }




        Member user = memberProvider.findByUserNameOrMobilePhoneOrEmail(username.trim());

        if (user == null) {
            return Message.error("您的用户名或密码错误！");
        }



        if (!StringUtils.equals(user.getLogin_password(), DigestUtils.md5Hex(password))) {
            return Message.error("您的用户名或密码错误！");
        }
//		YuEbao yuEbao = yeahpaysProvider.findByUserId(user.getId());
//		if (yuEbao == null) {
//			YuEbao yuEbaoImpl = new YuEbao();
//			yuEbaoImpl.setUser_id(user.getId());
//			yeahpaysProvider.insert(yuEbaoImpl);
//		}
        session.setAttribute(Constants.PRINCIPAL_SESSION_NAME, user);
        user.setLast_ip(AppContext.getRemoteIp());
        user.setLast_time(MsDateUtils.getTime());
        user.setLogin_times(user.getLogin_times() + 1);
        memberProvider.updateById(user);
        return Message.success("登录成功");
    }


}
